function submitLogin(event) {
  event.preventDefault(); // 阻止表单提交

  const username = document.getElementsByName("username")[0].value.trim();
  const password = document.getElementsByName("password")[0].value.trim();
  const errorMessage = document.getElementById("login-errMsg");

  // 清空之前的错误提示
  errorMessage.innerText = "";

  // 检查用户名和密码是否为空
  if (username === "" || password === "") {
    errorMessage.innerText = "用户名和密码不能为空";
    return;
  }

  fetch("/cgi/login", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error(`服务器错误: ${response.status}`);
      }
      return response.json();
    })
    .then((data) => {
      if (data.success) {
        window.location.href = "/blog.html";
      } else {
        errorMessage.innerText = data.message;
      }
    })
    .catch((error) => {
      errorMessage.innerText = error.message || "网络错误，请稍后重试";
    });
}

function submitRegister(event) {
  event.preventDefault();

  const username = document.getElementsByName("register_username")[0].value.trim();
  const password = document.getElementsByName("register_password")[0].value.trim();
  const confirmPassword = document.getElementsByName("register_confirm_password")[0].value.trim();
  const errorMessage = document.getElementById("register-errMsg");

  // 清空之前的错误提示
  errorMessage.innerText = "";

  // 检查用户名、密码和确认密码是否为空
  if (username === "" || password === "" || confirmPassword === "") {
    errorMessage.innerText = "用户名、密码和确认密码不能为空";
    return;
  }

  if (password !== confirmPassword) {
    errorMessage.innerText = "密码和确认密码不一致";
    return;
  }

  fetch("/cgi/register", {
    method: "POST",
    headers: {
      "Content-Type": "application/x-www-form-urlencoded",
    },
    body: `username=${encodeURIComponent(username)}&password=${encodeURIComponent(password)}`,
  })
    .then((response) => {
      if (!response.ok) {
        throw new Error("网络错误");
      }
      return response.json();
    })
    .then((data) => {
      if (data.success) {
        switchToLogin();
        alert("注册成功，请登录！");
      } else {
        errorMessage.innerText = data.message;
      }
    })
    .catch((error) => {
      errorMessage.innerText = error.message || "网络错误，请稍后重试";
    });
}

function switchToRegister() {
  document.getElementById("login-container").classList.add("hidden");
  document.getElementById("register-container").classList.remove("hidden");
}

function switchToLogin() {
  document.getElementById("register-container").classList.add("hidden");
  document.getElementById("login-container").classList.remove("hidden");
}
